const fs = require("fs");
const path = require('path');
const puppeteer = require("puppeteer");
const rimraf = require('rimraf');
const directoryPath = './tailwindClassNames'

function generateIndexFile (folderPath) {
  const files = fs.readdirSync(folderPath);
  const moduleExports = files.map(file => {
    const fileName = path.parse(file).name;
    if (fileName === 'top-right-bottom-left') {
      return `exports.top = require('./${file}');
exports.right = require('./${file}');
exports.bottom = require('./${file}');
exports.left = require('./${file}');`;
    }
    if (fileName === 'margin') {
      return `exports.margin = require('./${file}');
exports['margin-top'] = require('./${file}');
exports['margin-right'] = require('./${file}');
exports['margin-bottom'] = require('./${file}');
exports['margin-left'] = require('./${file}');
`;
    }
    if (fileName === 'background-color') {
      return `exports['${fileName}'] = require('./${file}');
exports['background'] = require('./${file}');`;
    }

    if (fileName === 'text-color') {
      return `exports['color'] = require('./${file}');`;
    }
    if (fileName === 'whitespace') {
      return `exports['white-space'] = require('./${file}');`;
    }

    return `exports['${fileName}'] = require('./${file}');`;
  });

  const indexContent = moduleExports.join('\n');

  fs.writeFileSync(path.join(folderPath, 'index.js'), indexContent);
}

async function start (url) {
  const browser = await puppeteer.launch({ headless: false });
  try {
    console.warn("执行中...");
    async function getNavs () {
      const page = await browser.newPage();
      await page.setDefaultNavigationTimeout(60000);
      await page.goto(url);
      const selector = "#nav";
      await page.waitForSelector(selector);
      const list = await page.$$eval(
        `${selector} ul > li > ul > li > a`,
        items => {
          const arr = [];
          const needLinks = items.slice(22, -4);
          needLinks.forEach(item => {
            const key = item.href.replace('https://www.tailwindcss.cn/docs/', '')

            const value = item.href;
            arr.push({ key, value });
          });
          return arr;
        }
      );
      return list;
    }
    async function getClassNames (url, fileName) {
      const page = await browser.newPage();
      await page.setDefaultNavigationTimeout(60000);
      await page.goto(url);
      const selector = "#class-table";
      await page.waitForSelector(selector);
      const classNamesMap = await page.$$eval(`${selector} tbody tr`, items => {
        const map = {};
        items.forEach(item => {
          const columns = Array.from(item.querySelectorAll("td"));
          const value = columns[0].textContent.trim();
          const key = columns[1].textContent.trim();
          map[key] = value;
        });
        return map;
      });

      const data = JSON.stringify(classNamesMap);
      fs.writeFileSync(
        "./tailwindClassNames/" + fileName + ".js",
        "module.exports = " + data
      );
    }
    const list = await getNavs();
    console.info("获取navs成功....");
    for (const item of list) {
      console.info("执行" + item.key + ":" + item.value);
      await getClassNames(item.value, item.key);
    }
    await browser.close();
    console.info("正在生成入口文件...");
    generateIndexFile(directoryPath)
    console.info("执行完毕");
  } catch (error) {
    await browser.close();
    console.warn("出错了，请重试", error);
  }
}
// generateIndexFile(directoryPath)
rimraf.sync(directoryPath);
fs.mkdirSync(directoryPath)
start("https://www.tailwindcss.cn/docs/installation");

